﻿using log4net.Appender;
using log4net.Core;
using System;
using System.Linq;
using System.Text;

namespace SharpML.Api.Implementation
{
    /// <summary>
    /// Provides a simple pub/sub pattern for log4net without the need for subscriber plumbing
    /// </summary>
    public class SimpleLoggingPublisher : AppenderSkeleton
    {
        public delegate void LogActivityDelegate( Level level, string renderedMessage );
        public static event LogActivityDelegate Activity = delegate { };

        protected override void Append( log4net.Core.LoggingEvent loggingEvent )
        {
            // Locals
            StringBuilder sb = new StringBuilder();
            var moment = DateTime.Now;

            // Add message
            var level = loggingEvent.Level.ToString();
            var className = loggingEvent.LocationInformation.ClassName;
            sb.AppendLine( String.Format( 
                "[{0} +{1}]  {2}::{3}\r\n{4}", 
                moment.ToLocalTime(), 
                moment.Millisecond.ToString( "000" ),
                level,
                className, 
                loggingEvent.RenderedMessage 
            ) );

            // Exception included?
            if( loggingEvent.ExceptionObject != null )

                // It's just a demo project, compromise and send top of stack along with message
                sb.AppendLine( String.Join( "\r\n", loggingEvent.ExceptionObject.ToString().Split( new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries ).Take( 1 ) ) );

            // Notify subscribers
            SimpleLoggingPublisher.Activity( loggingEvent.Level, sb.ToString() );
        }

    }
}
